package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior>
        implements ApFollowBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    /**
     * 存储关注数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {
        //参数校验
        if (dto==null||dto.getArticleId()==null||dto.getFollowId()==null||dto.getUserId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询行为实体  主键
        ApBehaviorEntry behavior = apBehaviorEntryService.
                findByUserIdOrEquipmentId(dto.getUserId(), null);
        if (behavior==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存用户的关注行为
        ApFollowBehavior alb = getOne(Wrappers.<ApFollowBehavior>lambdaQuery()
                .eq(ApFollowBehavior::getEntryId, behavior.getId())
                .eq(ApFollowBehavior::getFollowId, dto.getFollowId()));

        if (alb==null){
            alb = new ApFollowBehavior();
            alb.setEntryId(behavior.getId());  // 行为实体主键
            alb.setCreatedTime(new Date());
            alb.setArticleId(dto.getArticleId());
            alb.setFollowId(dto.getFollowId());
            save(alb);
        }

        //返回

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
